import sys
import os.path

DATA_EXT = ["dis", "eos", "exp", "fas", "geo"]

def load_patterns(pname):
    fname = pname + ".dat"
    f_patterns = open(fname,'r')
    lines = f_patterns.readlines()
    patterns = {}
    
    k = 0
    kGo = True
    while kGo:
        l = lines[k]
        lhead = l.split()
        
        kGo = len(lhead) > 0
        if kGo:
            pname = lhead[0]
            py = int(lhead[1])
            px = int(lhead[2])
            
            patterns[pname] = []
            
            k = k + 1
            for ix in range(px):
                l = lines[k]
                pline = [int(s) for s in l.split()]
                patterns[pname].append(pline)
                k = k + 1
        pass
    return patterns
    
def stretch(arr, n):
    b = []
    for a in arr:
        b = b + [a for i in range(n)]
    return b

def run(problem_name):
    main_patterns = {}
    pp = []
    n = 1
    #   read
    f_problem = open(problem_name+'.dat', 'r')
    lines = f_problem.readlines()
    for l in lines:
        la = l.split()
        patterns_fname = la[0]
        vy = int(la[1])
        vx = int(la[2])
        if(len(la) > 3): n = int(la[3])
        
        patterns = load_patterns(patterns_fname)
        pp.append([vy, vx, patterns])
    #   construct
    for ext in DATA_EXT:
        main_patterns[ext] = []
    for p in pp:
        vy, vx, patterns = p
        for ext in DATA_EXT:
            ix = 0
            pattern = patterns[ext]
            px = len(pattern)
            py = len(pattern[0])
            while (ix * n) < vx:
                for k in range(n):
                    pline = []
                    for i in range(vy / (py * n)):
                        pline = pline + stretch(pattern[ix % px], n)
                    pline = pline + stretch(pattern[ix % px], n)[:vy % (py * n)]
                    main_patterns[ext].append(pline)
                ix = ix + 1
    #   write
    for ext in DATA_EXT:
        fname = problem_name + "." + ext
        f_pattern = open(fname, 'w')
        for pline in main_patterns[ext]:
            f_pattern.write(' ' + ' '.join([str(a) for a in pline]) + '\n')
        f_pattern.close()
    
def usage():
    print "%s [problem_name]" %os.path.basename(__file__)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        problem_name = sys.argv[1]        
        run(problem_name)
    else:
        usage()
        